package org.rescue.analysis.taxonomy;

/*
 * Implementation of a ConceptToRootReader. Since location is stored in three fields in
 * the us_gazetteer table, we join the concepts set to each column. In each join, 
 * the conceptToRoot list has different size and hence we need a separate SQL for each.
 * 
 */

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class LocationCToRReader { // implements ConceptToRootReader {
	final int CALL_COUNT = 3;
	ResultSet rs = null;
	
	public int getCallCount() {
		return CALL_COUNT;
	}
	
	public String getRootConcept() {
		return "USA";
	}
	
	public ResultSet getResultSet(PreparedStatement stmt, Connection conn, int callId) {
		try {
			switch(callId) {
			case 1:
				stmt = conn.prepareStatement(
				"SELECT feature_name, county, ST_alpha FROM concepts c, us_gazetteer g WHERE c.concept = g.feature_name;");
				rs = stmt.executeQuery();
				break;
			case 2:
				stmt = conn.prepareStatement(
				"SELECT county, ST_alpha FROM concepts c, us_gazetteer g WHERE c.concept = g.county;");
				rs = stmt.executeQuery();
				break;
			case 3:
				stmt = conn.prepareStatement(
				"SELECT ST_alpha FROM concepts c, us_gazetteer g WHERE c.concept = g.ST_alpha;");
				rs = stmt.executeQuery();
				break;
			default:
				System.err.println("Call to ConceptToRootReader.getCtoR with undefined callId");
			}	
		}catch (SQLException ex) {
			while (ex!=null){
				System.err.println("SQLException: " + ex.getMessage());
				System.err.println("SQLState: " + ex.getSQLState());
				System.err.println("VendorError: " + ex.getErrorCode());
				ex = ex.getNextException();
			}
		}
		return rs;		
	}

	public ArrayList<String> getNextCtoR(int callId) {
		ArrayList<String> CToR = new ArrayList<String>();
		try {
			switch(callId) {
			case 1:
				CToR.add(rs.getString("feature_name"));
				CToR.add(rs.getString("county"));
				CToR.add(rs.getString("ST_alpha"));
				System.out.println(CToR.get(0) + " : " + CToR.get(1) + " : " + CToR.get(2));
				break;
			case 2:
				CToR.add(rs.getString("county"));
				CToR.add(rs.getString("ST_alpha"));					
				System.out.println(CToR.get(0) + " : " + CToR.get(1));
				break;
			case 3:
				CToR.add(rs.getString("ST_alpha"));
//				System.out.println(CToR.get(0));
				break;
			default:
				System.err.println("Call to ConceptToRootReader.getCtoR with undefined callId");
			}
		}catch (SQLException ex) {
			while (ex!=null){
				System.err.println("SQLException: " + ex.getMessage());
				System.err.println("SQLState: " + ex.getSQLState());
				System.err.println("VendorError: " + ex.getErrorCode());
				ex = ex.getNextException();
			}
		}
		return CToR;
	}		
}
